package org.check.UI;

import java.awt.EventQueue;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JTable;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.DefaultComboBoxModel;
import javax.swing.table.DefaultTableModel;

import org.check.SQL.ConnectionPool;
import org.check.Util.XmlParser;
import org.check.VO.DBConnVO;
import org.check.VO.Server;

import java.awt.Color;
import javax.swing.JSeparator;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;

public class ConfigEditor extends JDialog {

	private JPanel contentPane;
	private JTable table;
	private JTextField text_dbName;
	private JTextField text_user;
	private JTextField text_dbPwd;
	private JTextField text_dbUser;
	private JTextField text_dbIP;
	private JTextField text_configName;
	private JComboBox comboBox_version;
	private JComboBox comboBox_dbType;
	private DefaultTableModel tableModel;
	private JLabel label_5;
	private List<DBConnVO> dbConnVOs;
	private int index;
	private DBConnVO dbConnVO;
	boolean isNew;
	private ConnectionPool connPool;

	private String filePath = "conns_config.xml";
	private JEditorPane editor_vpnInfo;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					List<DBConnVO> dbConnVOs = XmlParser.generateDBVOList("conns_config.xml");
					ConfigEditor frame = new ConfigEditor(dbConnVOs, dbConnVOs.size());
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */

	public ConfigEditor(List<DBConnVO> dbConnVOsin, final int index) {
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 531, 414);
		setModalityType(ModalityType.APPLICATION_MODAL);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		dbConnVOs = dbConnVOsin;
		if (index == dbConnVOs.size()) {
			dbConnVO = new DBConnVO();
			setTitle("新建配置");
			isNew = true;
		} else if (index < dbConnVOs.size()) {
			dbConnVO = dbConnVOs.get(index);
			setTitle("编辑配置");
			isNew = false;
		}
		this.index = index;

		JLabel label = new JLabel("跳转配置");
		label.setBounds(10, 42, 179, 15);
		contentPane.add(label);

		JLabel label_1 = new JLabel("数据库配置");
		label_1.setBounds(10, 162, 71, 15);
		contentPane.add(label_1);

		JButton button = new JButton("添加跳转机");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Vector<String> emptyVector = new Vector<String>();
				emptyVector.addElement("");
				emptyVector.addElement("");
				emptyVector.addElement("");
				emptyVector.addElement("");
				tableModel.addRow(emptyVector);
				table.setModel(tableModel);
			}
		});
		button.setBounds(398, 75, 104, 23);
		contentPane.add(button);

		JLabel lblIp = new JLabel("IP地址");
		lblIp.setBounds(30, 60, 54, 15);
		contentPane.add(lblIp);

		table = new JTable();

		tableModel = new DefaultTableModel(new Object[][] { { null, null, null, null }, },
				new String[] { "New column", "New column", "New column", "New column" }) {
			Class[] columnTypes = new Class[] { String.class, String.class, String.class, String.class };

			public Class getColumnClass(int columnIndex) {
				return columnTypes[columnIndex];
			}
		};

		table.setModel(tableModel);
		table.getColumnModel().getColumn(0).setPreferredWidth(135);
		table.getColumnModel().getColumn(1).setPreferredWidth(52);
		table.getColumnModel().getColumn(2).setPreferredWidth(76);
		table.getColumnModel().getColumn(3).setPreferredWidth(106);
		table.setBounds(30, 79, 358, 63);
		contentPane.add(table);

		JLabel label_2 = new JLabel("用户名");
		label_2.setBounds(214, 60, 54, 15);
		contentPane.add(label_2);

		JLabel label_3 = new JLabel("密码");
		label_3.setBounds(286, 60, 54, 15);
		contentPane.add(label_3);

		text_dbName = new JTextField();
		text_dbName.setBounds(131, 215, 126, 21);
		contentPane.add(text_dbName);
		text_dbName.setColumns(10);

		comboBox_dbType = new JComboBox();
		comboBox_dbType.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				if (e.getStateChange() == ItemEvent.SELECTED) {
					if (((String) comboBox_dbType.getSelectedItem()).equals("Oracle")) {
						label_5.setText("数据库实例名");
						dbConnVO.setDbtype("oracle");
						dbConnVO.setDriverType("oracle.jdbc.driver.OracleDriver");
					}
					if (((String) comboBox_dbType.getSelectedItem()).equals("SQLServer")) {
						label_5.setText("数据库名");
						dbConnVO.setDbtype("mssql");
						dbConnVO.setDriverType("com.microsoft.sqlserver.jdbc.SQLServerDriver");
					}
				}
			}
		});

		comboBox_dbType.setModel(new DefaultComboBoxModel(new String[] { "Oracle", "SQLServer" }));
		comboBox_dbType.setToolTipText("");
		comboBox_dbType.setBounds(376, 215, 126, 21);
		contentPane.add(comboBox_dbType);

		JLabel label_4 = new JLabel("数据库类型");
		label_4.setBounds(298, 218, 71, 15);
		contentPane.add(label_4);

		label_5 = new JLabel("数据库实例名");
		label_5.setBounds(26, 218, 95, 15);
		contentPane.add(label_5);

		text_user = new JTextField();
		text_user.setBounds(131, 246, 126, 21);
		contentPane.add(text_user);
		text_user.setColumns(10);

		JLabel label_6 = new JLabel("数据库用户名");
		label_6.setBounds(26, 249, 95, 15);
		contentPane.add(label_6);

		text_dbPwd = new JTextField();
		text_dbPwd.setBounds(131, 277, 126, 21);
		contentPane.add(text_dbPwd);
		text_dbPwd.setColumns(10);

		JLabel label_7 = new JLabel("数据库密码");
		label_7.setBounds(26, 280, 95, 15);
		contentPane.add(label_7);

		text_dbUser = new JTextField();
		text_dbUser.setBounds(131, 308, 126, 21);
		contentPane.add(text_dbUser);
		text_dbUser.setColumns(10);

		JLabel label_8 = new JLabel("表用户名");
		label_8.setBounds(27, 311, 94, 15);
		contentPane.add(label_8);

		JButton button_1 = new JButton("删除跳转机");
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int selectedRow = table.getSelectedRow();
				if (selectedRow != -1) {
					tableModel.removeRow(selectedRow);
				}
			}
		});
		button_1.setBounds(398, 108, 104, 23);
		contentPane.add(button_1);

		JButton button_2 = new JButton("保存并退出");
		button_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				if (!isNew) {
					if (JOptionPane.OK_OPTION==JOptionPane.showConfirmDialog(null, "配置将被覆盖，是否继续保存？", "警告", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE)&&save()) {
						XmlParser.updateFromDBVOList(filePath, dbConnVOs);
						JOptionPane.showMessageDialog(null, "已保存。", "提示", JOptionPane.PLAIN_MESSAGE);
						dispose();
					}
				}else {
					if (save()) {
						XmlParser.updateFromDBVOList(filePath, dbConnVOs);
						JOptionPane.showMessageDialog(null, "已保存。", "提示", JOptionPane.PLAIN_MESSAGE);
						dispose();
					}
				}
			}
		});
		button_2.setBounds(295, 339, 104, 23);
		contentPane.add(button_2);

		JButton button_3 = new JButton("直接退出");
		button_3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (JOptionPane.OK_OPTION==JOptionPane.showConfirmDialog(null, "未保存的配置将丢失，是否确认退出？", "警告", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE)) {
					dispose();
				}
			}
		});
		button_3.setBounds(409, 339, 93, 23);
		contentPane.add(button_3);

		JButton btnNewButton = new JButton("保存");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (!isNew) {
					if (JOptionPane.OK_OPTION==JOptionPane.showConfirmDialog(null, "配置将被覆盖，是否继续保存？", "警告", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE)&&save()) {
						XmlParser.updateFromDBVOList(filePath, dbConnVOs);
						JOptionPane.showMessageDialog(null, "已保存。", "提示", JOptionPane.PLAIN_MESSAGE);
					}
				}else {
					if (save()) {
						XmlParser.updateFromDBVOList(filePath, dbConnVOs);
						JOptionPane.showMessageDialog(null, "已保存。", "提示", JOptionPane.PLAIN_MESSAGE);
						isNew = false;
					}
				}
			}
		});
		btnNewButton.setBounds(192, 339, 93, 23);
		contentPane.add(btnNewButton);

		text_dbIP = new JTextField();
		text_dbIP.setBounds(131, 184, 126, 21);
		contentPane.add(text_dbIP);
		text_dbIP.setColumns(10);

		JLabel lblNewLabel = new JLabel("数据库IP");
		lblNewLabel.setBounds(27, 187, 94, 15);
		contentPane.add(lblNewLabel);

		JSeparator separator = new JSeparator();
		separator.setBounds(10, 152, 492, 2);
		contentPane.add(separator);

		JLabel label_10 = new JLabel("配置名称");
		label_10.setBounds(10, 10, 54, 15);
		contentPane.add(label_10);

		text_configName = new JTextField();
		text_configName.setBounds(74, 7, 115, 21);
		contentPane.add(text_configName);
		text_configName.setColumns(10);

		JSeparator separator_1 = new JSeparator();
		separator_1.setBounds(10, 35, 495, 9);
		contentPane.add(separator_1);

		comboBox_version = new JComboBox();
		comboBox_version.setModel(new DefaultComboBoxModel(new String[] { "SP8", "SP16", "2016Q2", "2016Q4" }));
		comboBox_version.setBounds(376, 184, 126, 21);
		contentPane.add(comboBox_version);

		JLabel label_9 = new JLabel("平台版本");
		label_9.setBounds(298, 187, 54, 15);
		contentPane.add(label_9);

		JLabel label_11 = new JLabel("端口");
		label_11.setBounds(161, 60, 54, 15);
		contentPane.add(label_11);
		
		JLabel lblVpn = new JLabel("VPN信息");
		lblVpn.setBounds(298, 249, 54, 15);
		contentPane.add(lblVpn);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(293, 266, 212, 63);
		contentPane.add(scrollPane);
		
		editor_vpnInfo = new JEditorPane();
		scrollPane.setViewportView(editor_vpnInfo);
		
		JButton button_4 = new JButton("测试连接");
		button_4.addActionListener(new ActionListener() {
			

			public void actionPerformed(ActionEvent e) {
				try {
					connPool = new ConnectionPool(dbConnVO);
				} catch (Exception dbe) {
					dbe.printStackTrace();
					JOptionPane.showMessageDialog(null, "连接失败", "提示", JOptionPane.PLAIN_MESSAGE);
					connPool=null;
					return;
				}
				JOptionPane.showMessageDialog(null, "连接成功", "提示", JOptionPane.PLAIN_MESSAGE);
				connPool=null;
			}
		});
		button_4.setBounds(30, 339, 93, 23);
		contentPane.add(button_4);

		if (null != dbConnVO) {
			text_configName.setText(XmlParser.unicodeDecode(dbConnVO.getName()));
			text_user.setText(dbConnVO.getUser());
			text_dbUser.setText(dbConnVO.getDBuser());
			text_dbPwd.setText(dbConnVO.getPassword());
			editor_vpnInfo.setText(dbConnVO.getVpnInfo());
			comboBox_version.setSelectedItem(dbConnVO.getVersion());
			String dbType = dbConnVO.getDbtype();
			String url = dbConnVO.getUrl();
			if (dbConnVO.getIsRoute()) {
				tableModel.removeRow(0);
				for (Server server : dbConnVO.getServers()) {
					Vector<String> emptyVector = new Vector<String>();
					emptyVector.addElement(server.getHost());
					emptyVector.addElement(server.getPort().toString());
					emptyVector.addElement(server.getUser());
					emptyVector.addElement(server.getPwd());
					tableModel.addRow(emptyVector);
					table.setModel(tableModel);
				}
			}
			if (dbType.equals("oracle")) {
				comboBox_dbType.setSelectedItem("Oracle");
				String[] urlSplit = url.split(":");
				text_dbName.setText(urlSplit[urlSplit.length - 1]);
				text_dbIP.setText(urlSplit[urlSplit.length - 3].substring(1));
			} else if (dbType.equals("mssql")) {
				comboBox_dbType.setSelectedItem("SQLServer");
				String[] urlSplit = url.split("=");
				text_dbName.setText(urlSplit[urlSplit.length - 1]);
				String[] urlSplit2 = url.split(":");
				text_dbIP.setText(urlSplit2[urlSplit2.length - 2].substring(2));

			} else if (dbType.equals("")) {
				text_dbName.setText("");
				text_dbIP.setText("");
			} else {
				text_dbName.setText("unknown");
				text_dbIP.setText("unknown");
			}

		}

	}

	public boolean save() {
		boolean save = false;
		String configName = text_configName.getText();
		String user = text_user.getText();
		String pwd = text_dbPwd.getText();
		String dbUser = text_dbUser.getText();
		String dbName = text_dbName.getText();
		String dbIP = text_dbIP.getText();
		String version = comboBox_version.getSelectedItem().toString();
		String vpnInfo = editor_vpnInfo.getText();
		DBConnVO dbConnVO = new DBConnVO();

		try {
			if (configName == null || configName.trim().equals("")) {
				throw new Exception("请输入配置名称！");
			} else if (dbIP == null || user.trim().equals("")) {
				throw new Exception("请输入数据库IP！");
			} else if (dbName == null || dbName.trim().equals("")) {
				throw new Exception("请输入数据库实例名/数据库名！");
			}  else if (user == null || user.trim().equals("")) {
				throw new Exception("请输入数据库用户名！");
			} else if (pwd == null || pwd.trim().equals("")) {
				throw new Exception("请输入数据库密码！");
			} else if (dbUser == null || dbUser.trim().equals("")) {
				throw new Exception("请输入表用户名！");
			} else {
				if (comboBox_dbType.getSelectedItem().equals("Oracle")) {
					dbConnVO.setDbtype("oracle");
					dbConnVO.setDriverType("oracle.jdbc.driver.OracleDriver");
					dbConnVO.setUrl("jdbc:oracle:thin:@" + dbIP + ":1521:" + dbName);
				} else if (comboBox_dbType.getSelectedItem().equals("SQLServer")) {
					dbConnVO.setDbtype("mssql");
					dbConnVO.setDriverType("com.microsoft.sqlserver.jdbc.SQLServerDriver");
					dbConnVO.setUrl("jdbc:sqlserver://" + dbIP + ":1433;databaseName=" + dbName);
				} else {
					throw new Exception("请选择数据库类型！");
				}
				dbConnVO.setName(configName);
				dbConnVO.setUser(user);
				dbConnVO.setPassword(pwd);
				dbConnVO.setDBuser(dbUser);
				dbConnVO.setVersion(version);
				dbConnVO.setVpnInfo(vpnInfo);
				boolean isRoute = false; // count jumphosts
				for (int i = 0; i < table.getRowCount(); i++) {
					List<String> rowContent = new ArrayList<String>();
					for (int j = 0; j < table.getColumnCount(); j++) {
						String content = (String) table.getModel().getValueAt(i, j);
						if (null != content && !content.equals("")) {
							rowContent.add(content);
						}
					}
					if (rowContent.size() == table.getColumnCount()) {
						Server server = new Server();
						server.setHost(rowContent.get(0));
						server.setPort(rowContent.get(1));
						server.setUser(rowContent.get(2));
						server.setPwd(rowContent.get(3));
						dbConnVO.addServer(server);
						isRoute = true;
					} else if (rowContent.size() == 0) {
						System.out.println("empty row");
					} else {
						throw new Exception("跳转信息不完整！");
					}
				}
				dbConnVO.setIsRoute(isRoute);
				save = true;
			}
		} catch (Exception e1) {
			JOptionPane.showMessageDialog(null, e1.getMessage(), "警告", JOptionPane.PLAIN_MESSAGE);
			return false;
		}
		if (save) {
			if (isNew) {
				dbConnVOs.add(dbConnVO);
			} else {
				dbConnVOs.set(index, dbConnVO);
			}
			return save;
		} else {
			JOptionPane.showMessageDialog(null, "配置未保存。", "提示", JOptionPane.PLAIN_MESSAGE);
			return false;
		}

	}
}
